package com.gy.zpchat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import im.zego.zim.callback.ZIMLoggedInCallback;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.enums.ZIMErrorCode;

import com.alibaba.fastjson.JSONObject;
import com.gy.zpchat.base.BaseCallBack;
import com.gy.zpchat.net.BaseOkHttpClient;
import com.gy.zpchat.ui.H5Activity;
import com.gy.zpchat.ui.MainActivity;
import com.gy.zpchat.ui.chat.room.ZIMRoomChatActivity;
import com.gy.zpchat.ui.setting.SettingActivity;
import com.gy.zpchat.util.AppLogger;
import com.gy.zpchat.util.PreferenceUtil;
import com.leon.lfilepickerlibrary.utils.StringUtils;

import java.io.IOException;

import im.zego.zpns.ZPNsManager;
import im.zego.zpns.util.ZPNsConfig;
import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {

    public static final String SP_FILE_NAME = "userinfo";
    public static final String SP_FILE_ID_KEY = "userID";
    public static final String SP_FILE_NAME_KEY = "userName";
    public static final String SP_FILE_LAST_PUSH_MODE = "push_mode";
    private static final int PUSH_MODE_FCM = 1;
    private static final int PUSH_MODE_MADE_IN_CHAIN = 2;
    private static final String TAG = "LoginActivity";
    public EditText phoneText;
    public EditText codeText;
    private CheckBox agreeCheckbox;
    private Button getCodeBt;
    private Boolean isAgreeChecked = false;

    private CountDownTimer countDownTimer;
    private int pushMode = PUSH_MODE_MADE_IN_CHAIN;
    private SharedPreferences sp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        phoneText = findViewById(R.id.phone);
        codeText = findViewById(R.id.code);
        getCodeBt = findViewById(R.id.getCode);
        agreeCheckbox = findViewById(R.id.agreeCheckbox);
        agreeCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 处理选中状态改变事件
                isAgreeChecked = isChecked;
            }
        });
    }


    private void registerZPNs() {
        ZPNsConfig zimPushConfig = new ZPNsConfig();
        String appType = PreferenceUtil.getInstance(this).getStringValue("appType", "0");
        if (appType != null && !appType.equals("")) {
            zimPushConfig.setAppType(Integer.parseInt(appType));
        }
        if (pushMode == PUSH_MODE_FCM) {
            zimPushConfig.enableFCMPush();
        } else if (pushMode == PUSH_MODE_MADE_IN_CHAIN) {
            zimPushConfig.enableHwBadge(true);
//            zimPushConfig.enableHWPush();
//            zimPushConfig.enableMiPush(, );
//            zimPushConfig.enableVivoPush(, );
//            zimPushConfig.enableOppoPush(, , );
        }

        if (pushMode == PUSH_MODE_FCM || pushMode == PUSH_MODE_MADE_IN_CHAIN) {
            ZPNsManager.setPushConfig(zimPushConfig);
            ZPNsManager.getInstance().registerPush(this.getApplication());
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //    ZPNsManager.getInstance().unregisterPush();
    }

    @Override
    protected void onResume() {
        super.onResume();
        String payload = "";
        String call_id = "";
        if (getIntent().getExtras() != null) {
            payload = getIntent().getExtras().getString("payload", "");
            call_id = getIntent().getExtras().getString("call_id", "");
        }
        AppLogger.getInstance().d("push payload:%s", payload);
        AppLogger.getInstance().d("push call_id:%s", call_id);
    }

    public void getCode(View view) {
        String phone = phoneText.getText().toString();
        if (StringUtils.isEmpty(phone)) {
            Toast.makeText(this, "手机号不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long seconds = millisUntilFinished / 1000;
                getCodeBt.setSaveEnabled(false);
                getCodeBt.setText(String.valueOf(seconds));
            }

            @Override
            public void onFinish() {
                getCodeBt.setText("重新获取验证码");
            }
        };
        BaseOkHttpClient.newBuilder()
                .addParam("phone", phone)
                .form()
                .url("/dlr-auth/oauth/getSmsCode")
                .build()
                .enqueue(new BaseCallBack() {
                    @Override
                    public void onSuccess(Object o) {
                        Toast.makeText(LoginActivity.this, "成功：" + o.toString(), Toast.LENGTH_SHORT).show();
                        countDownTimer.start();
                    }

                    @Override
                    public void onError(int code) {
                        Toast.makeText(LoginActivity.this, "错误编码：" + code, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(LoginActivity.this, "失败：" + msg, Toast.LENGTH_SHORT).show();
                    }
                });

    }

    public void onLogin(View view) {
        login();
    }

    private void login() {
        String phone = phoneText.getText().toString();
        if (StringUtils.isEmpty(phone)) {
            Toast.makeText(this, "手机号不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        String code = codeText.getText().toString();
        if (StringUtils.isEmpty(code)) {
            Toast.makeText(this, "验证码不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isAgreeChecked) {
            Toast.makeText(this, "请点击同意协议方可进入！", Toast.LENGTH_SHORT).show();
            return;
        }
        BaseOkHttpClient.newBuilder()
                .addParam("grant_type", "sms_code")
                .addParam("phone",phone)
                .addParam("code",code)
                .post()
                .form()
                .url("/dlr-auth/oauth/token")
                .build()
                .enqueue(new BaseCallBack() {
                    @Override
                    public void onSuccess(Object o) {
                        Log.d(TAG, "onSuccess: "+o.toString());
                        JSONObject jsonObject=JSONObject.parseObject(o.toString());
                        String accessToken = jsonObject.getString("access_token");
                        PreferenceUtil.getInstance(LoginActivity.this).setStringValue("access_token", accessToken);
                        KeyCenter.access_token = accessToken;
                        Toast.makeText(LoginActivity.this, "登录成功：" + o.toString(), Toast.LENGTH_SHORT).show();
                        //跳转
                        Intent intent = new Intent(LoginActivity.this, H5Activity.class);
//                        intent.putExtra("conversationID", roomID);
//                        intent.putExtra("conversationName", roomName);
//                        intent.putExtra("draft", draft);
//                        this.startActivity(intent);
                         startActivity(intent);
                    }

                    @Override
                    public void onError(int code) {
                        Toast.makeText(LoginActivity.this, "错误编码：" + code, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(LoginActivity.this, "失败：" + msg, Toast.LENGTH_SHORT).show();
                    }
                });
//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
//        } else {
//            // 登录
//            registerZPNs();
//            SDKManager.sharedInstance().login(userID, userName, new ZIMLoggedInCallback() {
//                @Override
//                public void onLoggedIn(ZIMError zimError) {
//                    if (zimError.code != ZIMErrorCode.SUCCESS) {
//                        Toast.makeText(LoginActivity.this, "Login failed error info : " + zimError.code.name(), Toast.LENGTH_LONG).show();
//                    } else {
//                        SharedPreferences.Editor editor = sp.edit();
//                        editor.putString(SP_FILE_ID_KEY, userID);
//                        editor.putString(SP_FILE_NAME_KEY, userName);
//                        editor.putInt(SP_FILE_LAST_PUSH_MODE, pushMode);
//                        editor.apply();
//                        // 登录成功，进入下个页面
//                        Intent intent = new Intent(getApplication(), MainActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }
//                }
//            });
//        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        SDKManager.sharedInstance().showDebugLog(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        SDKManager.sharedInstance().hideDebugLog(this);
    }

    public void toSetting(View view) {
        SettingActivity.actionStart(this);

    }
}
